const moment = require('moment')
const WebSocket = require('ws')
const pako = require('pako')
const log4js = require('log4js')
const config = require('../config/index')
const Redis = require('ioredis')
const redis = new Redis(config.redis)
const request = require('request-promise')

// 配置log4js
log4js.configure(config.log4js)
const logger = log4js.getLogger('火币Hahax WebSocket监控')

const wsUrl = 'wss://api.hadax.com/ws'
const symbolsUrl = 'https://api.hadax.com/v1/hadax/common/symbols'
const symbols = []

let timer = null

;(async () => {
  let res = await request({
    url: symbolsUrl,
    json: true
  })
  if (res.status === 'ok') {
    for (let item of res.data) {
      item['quote-currency'] === 'btc' && symbols.push(item['base-currency'] + item['quote-currency'])
    }
    init()
  } else {
    process.exit(-1)
  }
})()

function init () {
  let ws = new WebSocket(wsUrl)
  ws.on('open', () => {
    console.log('open')
    subscribe(ws)
  })
  ws.on('message', (data) => {
    let text = pako.inflate(data, {
      to: 'string'
    })
    let msg = JSON.parse(text)
    if (msg.ping) {
      ws.send(JSON.stringify({
        pong: msg.ping
      }))
    } else if (msg.tick) {
      handle(msg)
    } else {
      console.log(text)
    }
  })

  ws.on('close', () => {
    console.log('close')
    clearTimeout(timer)
    timer = setTimeout(() => {
      init()
    }, 2000)
  })

  ws.on('error', err => {
    console.log('error', err)
    logger.error(err)
    clearTimeout(timer)
    timer = setTimeout(() => {
      init()
    }, 2000)
  })
}

let recordList = {}

function handle (data) {
  let symbol = data.ch.split('.')[1]
  let channel = data.ch.split('.')[2]
  if (channel === 'kline') {
    let open = data.tick.open
    let close = data.tick.close
    let percent = ((close - open) / open * 100).toFixed(2)
    if (percent > 2) {
      let record = recordList[symbol]
      if (record && record.tick.id === data.tick.id) {
        record.tick = data.tick
        if (++record.times >= 10 && !record.publish) {
          record.publish = true
          let now = moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
          console.log(`币种：${symbol}, 涨幅：${percent}, 时间：${now}`)
          redis.publish('news', JSON.stringify({
            title: `${symbol.toUpperCase()}一分钟内涨幅：${percent}%`,
            source: '火币Hadax监控',
            symbol: symbol,
            newsTime: moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss'),
            getTime: now
          }))
        }
      } else {
        recordList[symbol] = {}
        recordList[symbol].times = 1
        recordList[symbol].publish = false
        recordList[symbol].tick = data.tick
      }
    }
  }
}

function subscribe (ws) {
  // 订阅K线
  for (let symbol of symbols) {
    ws.send(JSON.stringify({
      'sub': `market.${symbol}.kline.1min`,
      'id': `${symbol}`
    }))
  }
}
